import store from '../store/index.js'

// 页面白名单，不受拦截
const whiteList = [
	'/pages/index/index',
	'/pages/my/index',
	'/pages/helpSquare/index',
	'/pages/publishLostAndFind/index'
]

function hasPermission(url) {
	let token = ''

	if (store.getters.userInfo) {
		token = store.getters.userInfo.token
	}


	// 在白名单中或有token可以直接跳转
	if (whiteList.indexOf(url) !== -1 || token) {
		console.log('通过')
		return true
	}

	console.log('失败')
	return false
}


function hasUserDetail() {
	if (store.getters?.userInfo?.userInfoDetail) {
		console.log('有用户信息！')
		return true
	}
	console.log('没有用户信息')
	return false

}

uni.addInterceptor('switchTab', {
	invoke(e) {

		return true
	},
	success(e) {

	}
})


uni.addInterceptor('navigateTo', {
	// 页面跳转前进行拦截, invoke根据返回值进行判断是否继续执行跳转
	invoke(e) {
		console.log(e.url)
		if (!hasPermission(e.url)) {
			uni.showToast({
				title: "请先登录！",
				icon: 'none',
				duration: 500
			});
			setTimeout(() => {
				uni.reLaunch({
					url: '/pages/login/index'
				})

			}, 500)

			return false
		} else if (!hasUserDetail()) {
			uni.showToast({
				title: "请先将用户信息补充完整！",
				icon: 'none',
				duration: 500
			});
			setTimeout(() => {
				uni.reLaunch({
					url: '/pages/maintainUserInfo/index'
				})

			}, 500)
			return false
		}
		return true
	},
	success(e) {

	}
})

uni.addInterceptor('switchTab', {
	// tabbar页面跳转前进行拦截
	invoke(e) {
		if (!hasPermission(e.url)) {
			uni.reLaunch({
				url: '/pages/login/index'
			})
			console.log('不在白名单内')
			return false
		}
		console.log('在白名单内')
		return true
	},
	success(e) {

	}
})